<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="系部" prop="college">
        <el-input v-model="queryParams.college" placeholder="请输入系部" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="advancedStatus">
        <el-select v-model="queryParams.advancedStatus" placeholder="请选择" clearable style="width: 240px">
          <el-option v-for="dict in dict.type.advanced_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="推荐项" prop="researchtopic">
        <el-select
          v-model="queryParams.researchtopic"
          placeholder="推荐项"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in recommendOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item> -->

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="goRank"
        >录入排名</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" v-hasPermi="['eqxm:advanced:collegeAccreditation']"
          @click="collegeAccreditation">系部评审</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain size="mini" v-hasPermi="['eqxm:advanced:recommendAdvanced']"
          @click="recommendAdvanced">推荐先进个人</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="teamList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="姓名/学号" align="center" prop="name">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}/{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="团队名称" align="center" prop="teamName" />
      <el-table-column label="指导单位" align="center" prop="college" />
      <el-table-column label="打卡情况" align="center" prop="clockCount">
        <template slot-scope="scope">
          <span>{{ scope.row.actualClock }}/{{ scope.row.shouldClock }}</span>
        </template>
      </el-table-column>
      <el-table-column label="团队相关材料" align="center" class-name="small-padding fixed-width">
        <!-- <template slot-scope="scope">
			  <el-button
			    size="mini"
			    type="text"
			    icon="el-icon-edit"
			    @click="goTeamInfo(scope.row)"
			  >查看</el-button>
	   </template> -->
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-document" @click="teamDetail(scope.row)">团队信息</el-button>
          <!-- v-hasPermi="['practicalAch:schoolmatchScore:teamDetail']" -->
          <el-button size="mini" type="text" icon="el-icon-document" @click="seeUpload(scope.row, '3')">宣传材料</el-button>
          <!-- v-hasPermi="['practicalAch:schoolmatchScore:sumDetail']" -->
        </template>
      </el-table-column>
      <el-table-column label="个人总结" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <el-button size="mini" type="text" v-hasPermi="['eqxm:advanced:edit']" icon="el-icon-edit"
            @click="handleDownload(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="系部评分" align="center" prop="collegeScore" />
      <el-table-column label="奖项" align="center" prop="advancedPrize" />
      <el-table-column label="状态" align="center" prop="advancedStatus">
        <template slot-scope="scope">
          <!-- 默认0待审核，1审核通过，2审核拒绝，3推荐 4.颁奖-->
          <dict-tag :options="dict.type.advanced_status" :value="scope.row.advancedStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" v-hasPermi="['eqxm:advanced:check']"
            :disabled="scope.row.advancedStatus != '0'" @click="examineOpen(scope.row)">审核</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" v-hasPermi="['eqxm:advanced:prize']"
            :disabled="scope.row.advancedStatus != '3'" @click="advancedPrizeOpenF(scope.row)">颁奖</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" v-hasPermi="['eqxm:advanced:delRecommend']"
            :disabled="scope.row.advancedStatus != '3'" @click="delRecommend(scope.row)">取消推荐</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" v-hasPermi="['eqxm:advanced:delprize']"
            :disabled="scope.row.advancedStatus != '4'" @click="recommendAdvanced(scope.row)">取消颁奖</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 颁奖对话框 -->
    <el-dialog title="颁奖" :visible.sync="advancedPrizeOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="奖项名称" prop="advancedPrize">
          <el-input v-model="advancedPrize" placeholder="请输入奖项名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="advancedPrizeSubmitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改团队对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="审核意见" prop="creditExamineComments">
          <el-input v-model="creditExamineComments" placeholder="请输入审核意见" />
        </el-form-item>
        <el-button type="primary" @click="submitForm('2')">审核拒绝</el-button>
        <el-button type="primary" @click="submitForm('1')">审核通过</el-button>
      </el-form>
      <!--      <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </div> -->
    </el-dialog>

    <el-dialog title="系部评审" :visible.sync="psOpen" width="500px" append-to-body>
      <el-table border :data="psList" @selection-change="handleSelectionChange">
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="分数" align="center" prop="collegeScore">
          <template slot-scope="scope">
            <el-input v-model.number="scope.row.collegeScore"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="psSubmitForm">确 定</el-button>
      </div>
    </el-dialog>
    
    <el-dialog title="团队信息" :visible.sync="teamManageOpen" width="1200px" append-to-body>
      <teamManageInfo ></teamManageInfo>
    </el-dialog>
    <el-dialog title="宣传材料" :visible.sync="seeUploadOpen" width="1200px" append-to-body>
      <seeUploadInfo ></seeUploadInfo>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTeam,
  getTeam,
  delTeam,
  addTeam,
  updateTeam,
  exportTeam,
  downloadTemplateTeam,
} from '@/api/eqxm/team';
import {
  psSubmitForm,
  listTeamStudent,
  getTeamStudent,
  delTeamStudent,
  addTeamStudent,
  updateTeamStudent,
  exportTeamStudent,
  listAdvanced,
  listCollegeAccreditation,
  downloadTemplate,
} from '@/api/eqxm/teamStudent';
import { examine, toAward, recommendAdvanced } from '@/api/eqxm/advanced';
import teamManageInfo from "@/views/eqxm/schoolmatchRecommend/teamManage";
import seeUploadInfo from "@/views/eqxm/schoolmatchRecommend/seeUpload";
import { mapGetters } from 'vuex';
import CommonUtils from '@/utils/CommonUtils';
export default {
  name: 'Team',
  components: {
    teamManageInfo,
    seeUploadInfo
  },
  dicts: ['advanced_status'],
  computed: {
    ...mapGetters(['name', 'userName']),
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 团队表格数据
      teamList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        college: null,
        researchtopic: null,
        isimportant: null,
        presentation: null,
        presentationdetail: null,
        transportation: null,
        accommodation: null,
        publicity: null,
      },
      // 表单参数
      form: {},
      creditExamineComments: null,
      // 表单校验
      rules: {},
      recommendOptions: [],
      advancedPrizeOpen: false,
      advancedPrize: '',
      psOpen: false,
      psList: [],

      applyType: null,
      typeList: null,

      teamManageOpen:false,
      seeUploadOpen:false,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询团队列表 */
    getList() {
      this.loading = true;
      listAdvanced(this.queryParams).then(response => {
        console.log(response.data);
        this.teamList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //多选数据处理后selection禁用
    checkboxSelect(row, rowIndex) {
      if (row.advancedStatus == '1' || row.advancedStatus == '2') {
        return false; // 禁用
      } else {
        return true; // 不禁用
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        delFlag: null,
        college: null,
        createBy: null,
        researchtopic: null,
        isimportant: null,
        createTime: null,
        presentation: null,
        updateBy: null,
        presentationdetail: null,
        updateTime: null,
        transportation: null,
        accommodation: null,
        publicity: null,
        advancedPrize: '',
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.typeList = selection.map(item => item.type);
      console.log('lsit');
      console.log(this.ids, this.typeList, 'list');
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      //清空store的项目信息
      let teamInfo = {
        id: '',
      };
      CommonUtils.setCurTeamInfo(teamInfo);
      const vm = this;
      vm.$router.push({
        //核心语句
        path: '/team/teamManage', //跳转的路径
        query: { type: 0 },
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();

      const vm = this;
      vm.$router.push({
        //核心语句
        path: '/advanced/look/' + row.id, //跳转的路径
      });
    },
    upload(row) {
      this.reset();
      let teamInfo = {
        id: row.id,
      };
      CommonUtils.setCurTeamInfo(teamInfo);
      const vm = this;
      vm.$router.push({
        //核心语句
        path: '/team/upload', //跳转的路径
        query: { type: 0 },
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTeam(this.form).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess('修改成功');
                this.open = false;
                this.getList();
              }
            });
          } else {
            addTeam(this.form).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess('新增成功');
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除团队编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return delTeam(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有团队数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return exportTeam(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    },
    recommendTeam() {
      let teamInfo = {
        id: '',
      };
      CommonUtils.setCurTeamInfo(teamInfo);
      const vm = this;
      vm.$router.push({
        //核心语句
        path: '/schoolmatch/recommendTeam', //跳转的路径
      });
    },
    judge() {
      let teamInfo = {
        id: '',
      };
      CommonUtils.setCurTeamInfo(teamInfo);
      const vm = this;
      vm.$router.push({
        //核心语句
        path: '/schoolmatch/judge', //跳转的路径
      });
    },
    review() {
      let teamInfo = {
        id: '',
      };
      CommonUtils.setCurTeamInfo(teamInfo);
      const vm = this;
      vm.$router.push({
        //核心语句
        path: '/schoolmatch/review', //跳转的路径
      });
    },
    collegeScore() {
      let teamInfo = {
        id: '',
      };
      CommonUtils.setCurTeamInfo(teamInfo);
      const vm = this;
      vm.$router.push({
        //核心语句
        path: '/schoolmatch/collegeScore', //跳转的路径
      });
    },
    goApply() {
      const vm = this;
      vm.$router.push({
        //核心语句
        path: '/advanced/apply', //跳转的路径
      });
    },
    goRank() {
      const vm = this;
      vm.$router.push({
        //核心语句
        path: '/advanced/rank', //跳转的路径
      });
    },
    examineOpen(row) {
      this.form = row;
      this.creditExamineComments = '';
      this.teamStudentId = row.id;
      this.open = true;
    },
    examineOpenS() {
      const userIds = this.ids;
      if (userIds.length == 0) {
        this.$modal.msgError('请选择');
        return;
      }
      this.form = { creditExamineComments: '' };
      this.manyExamine = true;
      this.open = true;
    },
    // 取消推荐
    delRecommend(row) {
      this.$confirm('确认取消推荐？', '提示', { type: 'warning' }).then(() => {
        this.teamStudentId = row.id;
        this.form.type = row.type;
        this.submitForm(1);
      });
    },
    /** 提交按钮 */
    submitForm(res) {
      let subForm = {};
      subForm.advancedStatus = res;
      subForm.examineComments = this.creditExamineComments;
      subForm.id = this.teamStudentId;
      subForm.type = this.form.type;
      examine(subForm).then(response => {
        this.$modal.msgSuccess('审核成功');
        this.getList();
        this.open = false;
      });
    },
    recommendAdvanced(row) {
      const userIds = row.id || this.ids;
      var dataList = [];
      console.log(userIds, this.typeList, 'aaa');
      if (row.id) {
        dataList = [{
          id: userIds,
          type: row.type,
          advancedPrize: ''
        }]
      } else {
        for (let i = 0; i < userIds.length; i++) {
          dataList.push({
            id: userIds[i],
            type: this.typeList[i],
            advancedPrize: '',
          });
          // dataList[i].id = userIds[i];
          // dataList[i].type = this.typeList[i];
        }
      }
      if (userIds.length == 0) {
        this.$modal.msgError('请选择');
        return;
      }
      this.$modal
        .confirm('确认推荐？')
        .then(function () {
          return recommendAdvanced(dataList);
        })
        .then(response => {
          this.$modal.msgSuccess('推荐成功');
          this.getList();
          this.open = false;
        })
        .catch(() => { });
      //  recommendAdvanced(userIds).then(response => {
      //  		  this.$modal.msgSuccess("推荐成功");
      //  		  this.getList();
      //  		  this.open=false
      //  });
    },
    advancedPrizeOpenF(row) {
      this.teamStudentId = row.id;
      this.applyType = row.type;
      this.advancedPrize = '';
      this.advancedPrizeOpen = true;
    },
    advancedPrizeSubmitForm() {
      let advancedPrizeFrom = {};
      advancedPrizeFrom.id = this.teamStudentId;
      advancedPrizeFrom.advancedStatus = '4';
      advancedPrizeFrom.advancedPrize = this.advancedPrize;
      advancedPrizeFrom.type = this.applyType;
      toAward(advancedPrizeFrom).then(response => {
        if (response.code == 200) {
          this.$modal.msgSuccess('颁奖成功');
          this.getList();
          this.advancedPrizeOpen = false;
        }
      });
    },
    collegeAccreditation() {
      listCollegeAccreditation().then(response => {
        if (response.code == 200) {
          this.psList = response.rows;
          this.loading = false;
          this.psOpen = true;
        }
      });
    },
    goTeamInfo(row) {
      this.reset();
      let teamInfo = {
        id: row.teamid,
      };
      CommonUtils.setCurTeamInfo(teamInfo);
      const vm = this;
      vm.$router.push({
        //核心语句
        path: '/team/teamManage', //跳转的路径
        query: { type: 0 },
      });
    },
    /** 团队信息按钮 */
    teamDetail(row) {
      this.reset();
      let teamInfo = {
        id: row.teamId,
      };
      CommonUtils.setCurTeamInfo(teamInfo);
      const vm = this;
      // vm.$router.push({
      //   //核心语句
      //   path: '/schoolmatchRecommend/teamManage', //跳转的路径
      //   query: { type: 0 },
      // });
      this.teamManageOpen = true;
    },
    seeUpload(row, uploadId) {
      // debugger
      let teamInfo = {
        id: row.teamId,
      };
      CommonUtils.setCurTeamInfo(teamInfo);
      this.seeUploadOpen = true;
      // const vm = this;
      // vm.$router.push({
      //   //核心语句
      //   path: '/schoolmatchRecommend/seeUpload/' + uploadId, //跳转的路径
      // });
    },
    /** 下载按钮操作 */
    handleDownload(row) {
      window.open(process.env.VUE_APP_BASE_API + `/eqxm/teamStudent/handleDownload/${row.id}/${row.type}`);
      // this.download(
      //     '/eqxm/teamStudent/handleDownload/${row.id}',
      //     {
      //       ...this.queryParams,
      //     },
      //     `type_${new Date().getTime()}.xlsx`
      //   );
      // this.reset();
      // const id = row.id || this.ids;
      // downloadTemplate(id).then((response) => {
      //   // this.download(response);
      //   if (response != undefined || response != null) {
      // 	if (response.data.size > 0) {
      // 	  let fileName = decodeURI(response.headers.contentfile);

      // 	  let contentType = "application/x-msdownload;";
      // 	  let blob = new Blob([response.data], {
      // 		type: contentType + "charset=UTF-8",
      // 	  });
      // 	  if (window.navigator.msSaveOrOpenBlob) {
      // 		//IE10+下载
      // 		navigator.msSaveBlob(blob, fileName);
      // 	  } else {
      // 		// 非IE下载
      // 		var link = document.createElement("a");
      // 		link.href = window.URL.createObjectURL(blob);
      // 		link.download = fileName;
      // 		link.click();
      // 		//释放内存
      // 		window.URL.revokeObjectURL(link.href);
      // 	  }
      // 	}
      //   }
      // });
    },
    /** 下载按钮操作 */
    handleDownloadTeam(row) {
      this.reset();
      const id = row.teamid;
      downloadTemplateTeam(id).then(response => {
        if (response != undefined || response != null) {
          if (response.data.size > 0) {
            let fileName = decodeURI(response.headers.contentfile);

            let contentType = 'application/x-msdownload;';
            let blob = new Blob([response.data], {
              type: contentType + 'charset=UTF-8',
            });
            if (window.navigator.msSaveOrOpenBlob) {
              //IE10+下载
              navigator.msSaveBlob(blob, fileName);
            } else {
              // 非IE下载
              var link = document.createElement('a');
              link.href = window.URL.createObjectURL(blob);
              link.download = fileName;
              link.click();
              //释放内存
              window.URL.revokeObjectURL(link.href);
            }
          }
        }
      });
    },
    psSubmitForm() {
      psSubmitForm(this.psList).then(response => {
        this.$modal.msgSuccess('打分成功');
        this.getList();
        this.psOpen = false;
      });
    },
  },
};
</script>
